package com.soledroid;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import org.xml.sax.helpers.DefaultHandler;

public class SAXTimeTableParser extends DefaultHandler{

	LunchTime[] myLunchTimes = new LunchTime[7];

	private String tempVal;

	//to maintain context
	int currentDay;
	int start, end;


	public SAXTimeTableParser(){
		for(int i = 0; i < 7; i++) {
			myLunchTimes[i] = new LunchTime();
		}
	}

	public void run(String url) {
		parseDocument(url);
		//printData();
	}

	private void parseDocument(String url) {

		//get a factory
		SAXParserFactory spf = SAXParserFactory.newInstance();
		try {

			//get a new instance of parser
			SAXParser sp = spf.newSAXParser();

			//parse the file and also register this class for call backs
			sp.parse(url, this);

		}catch(SAXException se) {
			se.printStackTrace();
		}catch(ParserConfigurationException pce) {
			pce.printStackTrace();
		}catch (IOException ie) {
			ie.printStackTrace();
		}
	}

	/**
	 * Iterate through the list and print
	 * the contents
	 */
	private void printData(){

		//System.out.println("No of Employees '" + myEmpls.size() + "'.");

		/*Iterator it = myLunchTimes.iterator();
		while(it.hasNext()) {
			System.out.println(it.next().toString());
		}*/

		for(int i = 0; i < 7; i++) {
			System.out.println(myLunchTimes[i].getLunchTime());
		}
	}
	
	public String getDataString() {
		String line = "";
		for(int i = 0; i < 7; i++) {
			line = line + myLunchTimes[i].getLunchTime() + " ";
		}
		return line;
	}


	//Event Handlers
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		//reset
		tempVal = "";
		if(qName.equalsIgnoreCase("Data_Timetable_Student")) {
			//create a new instance of employee
			//tempTime = new LunchTime();
		}
	}


	public void characters(char[] ch, int start, int length) throws SAXException {
		tempVal = new String(ch,start,length);
	}

	public void endElement(String uri, String localName, String qName) throws SAXException {

		if(qName.equalsIgnoreCase("Data_Timetable_Student")) {
			//add it to the list
			myLunchTimes[currentDay].Update(start, end);

		}else if (qName.equalsIgnoreCase("DayCode")) {
			currentDay = Integer.parseInt(tempVal) - 1;
		}else if (qName.equalsIgnoreCase("StartTime")) {
			start = Integer.parseInt(tempVal)/100;
		}else if (qName.equalsIgnoreCase("EndTime")) {
			end = Integer.parseInt(tempVal)/100;
		}

	}

	/*public static void main(String[] args){
		SAXTimeTableParser spe = new SAXTimeTableParser();
		spe.run();
	}*/

}




